package com.example.dllo.my36kr.news.newsecond;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.LabeledIntent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.Scroller;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.dllo.my36kr.R;
import com.example.dllo.my36kr.my.MyUser;
import com.example.dllo.my36kr.my.collect.CollectBean;
import com.example.dllo.my36kr.my.collect.CollectUser;
import com.example.dllo.my36kr.news.html.HtmlTextView;
import com.example.dllo.my36kr.news.newsecond.listener.ScrollViewListener;
import com.example.dllo.my36kr.news.newsecond.window.SecondWindow;
import com.example.dllo.my36kr.news.newsecond.window.WindowBean;
import com.example.dllo.my36kr.tools.BaseAty;
import com.example.dllo.my36kr.tools.DBTool;
import com.example.dllo.my36kr.tools.MyApp;
import com.example.dllo.my36kr.tools.NetTool;
import com.example.dllo.my36kr.tools.StaticUrl;
import com.litesuits.orm.LiteOrm;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * Created by dllo on 16/8/22.
 */
public class SecondActivity extends BaseAty implements ScrollViewListener, View.OnClickListener {

    TextView titleTv, nameTv, timeTv;
    ImageView avatarIv;
    HtmlTextView contentTv;
    SimpleDateFormat mformat;
    private LinearLayout layout;
    private SecondWindow window;
    private String ss;
    private TextView briefTv;
    private SecondScrollView scrollView;
    private LinearLayout below;
    private ImageButton backIb;
    private String url;
    private Intent intent;
    private SecondBean data;
    private LiteOrm liteOrm;
    private SecondActivity.mySet mySet;
    private ImageButton collectInb;


    @Override
    protected int setLayout() {
        return R.layout.activity_second;
    }


    @Override
    protected void initView() {

        mformat = new SimpleDateFormat("HH:mm");//second 中设置的时间

        briefTv = bindView(R.id.tv_second_author_brief);//从SecondWindow 中获取的brief

        scrollView = bindView(R.id.sv_activity_second);//自定义ScrollView


        final ImageButton setBnt = bindView(R.id.ib_activity_search_set);//设置
        mySet = new mySet(SecondActivity.this, itemsOnClicko);
        setBnt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mySet.showAsDropDown(setBnt, 0, -200);
            }
        });


        below = bindView(R.id.ll_below);//下显示 小抽屉
        backIb = bindView(R.id.ib_activity_second_back);
        backIb.setOnClickListener(this);
        //收藏
        collectInb = bindView(R.id.ib_activity_search_collect);
        collectInb.setOnClickListener(this);
        ImageButton sheraIb = bindView(R.id.ib_activity_search_share);//分享
        sheraIb.setOnClickListener(this);
        contentTv = bindView(R.id.tv_activity_second_content);//second 中的内容
        titleTv = bindView(R.id.tv_activity_second_title);//second 中的title
        avatarIv = bindView(R.id.iv_second_author_avatar);//second 中 作者同学
        nameTv = bindView(R.id.tv_second_author_name);//second 中 作者名字
        timeTv = bindView(R.id.tv_second_author_time);//second 时间显示
        layout = bindView(R.id.ll_activity_second);//点击的布局 显示SecondWindow
        window = new SecondWindow(SecondActivity.this, itemsOnClick);
        layout.setOnClickListener(new View.OnClickListener() {//对SecondWindow设点击事件
            @Override
            public void onClick(View v) {
                window.showAsDropDown(findViewById(R.id.ll_activity_second));//点击布局的ID
                window.setA(ss);//向SecondWindow传值feedId
            }
        });
        scrollView.setScrollViewListener(this);
    }

    private View.OnClickListener itemsOnClicko = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mySet.dismiss();//SecondWindow 点击关闭

        }
    };

    @Override
    protected void initData() {

        liteOrm = LiteOrm.newSingleInstance(this, "MyDataBase.db");
        intent = getIntent();
        ss = intent.getStringExtra("details");//从newFragment 中获取feedId
        url = StaticUrl.NEWS_DETAILS_URL + ss;
        mNetTool.getNetData(url, SecondBean.class, new NetTool.NetListener<SecondBean>() {//网址拼接
            @Override
            public void onSuccess(SecondBean secondBean) {
                data = secondBean;
                String html = secondBean.getData().getContent();//去掉其中的符号
                html.trim();
                html = html.replace("<p >", "<p>");
                html = html.replace("<blockquote >", "");
                html = html.replace("</blockquote>", "");
                html = html.replace("<br/>", "");
                html = html.replace("<ul  class=\" list-paddingleft-2\">", "");
                html = html.replace("</ul>", "");
                html = html.replace("</li>", "");
                html = html.replace("<li>", "");
                contentTv.setHtmlFromString(html, false);


                BmobUser user =  BmobUser.getCurrentUser(BmobUser.class);
                DBTool.getInstance().unRepetition("postId = ?", data.getData().getPostId(), "xM = ?", user.getUsername(), new DBTool.QueryListener() {
                    @Override
                    public void onQueryComplete(ArrayList<CollectBean> nativeBeen) {//收藏图片的显示与隐藏
                        if (nativeBeen.size() != 0){
                            collectInb.setImageResource(R.mipmap.favorite_blue);
                        }else {
                            collectInb.setImageResource(R.mipmap.news_toolbar_icon_favorite);
                        }
                    }
                });
                titleTv.setText(secondBean.getData().getTitle());
                nameTv.setText(secondBean.getData().getUser().getName());
                mNetTool.getImage(secondBean.getData().getUser().getAvatar(), avatarIv);
                Long now = System.currentTimeMillis();
                long dTime = now - Long.valueOf(secondBean.getData().getPublishTime());
                SimpleDateFormat nFormat = new SimpleDateFormat("dd");
                int nNow = Integer.parseInt(nFormat.format(now)) - Integer.parseInt(nFormat.format(Long.valueOf(secondBean.getData().getPublishTime())));
                if (nNow >= 1) {
                    timeTv.setText(nNow + "天之前");
                } else if (dTime > 1000 * 60 * 60) {
                    //显示正常日期
                    String time = mformat.format(Long.valueOf(dTime));
                    timeTv.setText(time);

                } else if (dTime > 1000 * 60) {
                    //显示多长分钟之前
                    String min = String.valueOf((int) dTime / 1000 / 60);
                    timeTv.setText(min + "分钟之前");
                } else {
                    //显示多少s之前
                    String second = String.valueOf((int) dTime / 1000);
                    timeTv.setText(second + "s之前");
                }
                mNetTool.getNetData(StaticUrl.NEWS_AUTHOR_URL + ss + "/author-region", WindowBean.class, new NetTool.NetListener<WindowBean>() {
                    @Override
                    public void onSuccess(WindowBean windowBean) {
                        briefTv.setText(windowBean.getData().getBrief());//从SecondWindow 获取brief 的值
                    }

                    @Override
                    public void onError(String errorMsg) {

                    }
                });
            }

            @Override
            public void onError(String errorMsg) {

            }
        });
    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            window.dismiss();//SecondWindow 点击关闭

        }
    };

    @Override
    public void onScrollChanged(SecondScrollView scrollView, int x, int y, int oldx, int oldy) {

        if (y == 0) {
            below.setVisibility(View.VISIBLE);
            //补间动画 旋转
            RotateAnimation ra = new RotateAnimation(0,360,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
            ra.setDuration(2000);
            ra.setRepeatCount(1);
            below.startAnimation(ra);

        } else {
            below.setVisibility(View.GONE);
        }

    }

    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
//        oks.setTitle(getString(R.string.share));
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

// 启动分享GUI
        oks.show(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_activity_second_back:
                finish();
                break;
            case R.id.ib_activity_search_collect:
                ss = intent.getStringExtra("details");//从newFragment 中获取feedId
                url = StaticUrl.NEWS_DETAILS_URL + ss;
                final BmobUser user =  BmobUser.getCurrentUser(BmobUser.class);
                final CollectUser collectUser = new CollectUser();
                collectUser.setName(user.getUsername());
                collectUser.setCollect(url);
                collectUser.setFeedId(ss);
                collectUser.save(new SaveListener<String>() {
                    @Override
                    public void done(String s, BmobException e) {
                        if (e == null) {
                            Toast.makeText(SecondActivity.this, "网络收藏成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(SecondActivity.this, "网络收藏失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

                DBTool.getInstance().unRepetition("postId = ?", data.getData().getPostId(), "xM = ?", user.getUsername(), new DBTool.QueryListener() {
                    @Override
                    public void onQueryComplete(ArrayList<CollectBean> nativeBeen) {
                        if (nativeBeen.size() != 0) {
                            liteOrm.delete(nativeBeen);
                            collectInb.setImageResource(R.mipmap.news_toolbar_icon_favorite);
                            Toast.makeText(SecondActivity.this, "取消收藏", Toast.LENGTH_SHORT).show();
                        } else {
                            collectInb.setImageResource(R.mipmap.favorite_blue);
                            CollectBean bean1 = new CollectBean();
                            bean1.setxM(user.getUsername());
                            bean1.setPostId(data.getData().getPostId());
                            bean1.setName(data.getData().getUser().getName());
                            bean1.setColumnName(data.getData().getColumnName());
                            bean1.setPublishTime(data.getData().getPublishTime());
                            bean1.setUrl(data.getData().getFeatureImg());
                            bean1.setTitle(data.getData().getTitle());
                            bean1.setColumnId(data.getData().getColumnId());
                            DBTool.getInstance().insertUser(bean1);
                            Toast.makeText(SecondActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
                        }

                    }
                });


                break;
            case R.id.ib_activity_search_share:
                showShare();
                break;
        }
    }

    public class mySet extends PopupWindow {
        public mySet(Context context, View.OnClickListener itemsOnClick) {
            super(context);
            View view = LayoutInflater.from(context).inflate(R.layout.set_my, null);
            SeekBar seekBar = (SeekBar) view.findViewById(R.id.sb_set_my);
            seekBar.setMax(255);
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    if (fromUser) {
                        Integer tmpInt = seekBar.getProgress();
                        android.provider.Settings.System.putInt(getContentResolver(),
                                Settings.System.SCREEN_BRIGHTNESS, tmpInt);
                        tmpInt = Settings.System.getInt(getContentResolver(),
                                Settings.System.SCREEN_BRIGHTNESS, -1);
                        WindowManager.LayoutParams lp = getWindow().getAttributes();
                        if (0 <= tmpInt && tmpInt <= 255) {
                            lp.screenBrightness = tmpInt / 255.0f;
                        }
                        getWindow().setAttributes(lp);
                    }

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });
            this.setContentView(view);
            this.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
            //设置SelectPicPopupWindow弹出窗体的高
            this.setHeight(LinearLayout.LayoutParams.MATCH_PARENT);
            //设置SelectPicPopupWindow弹出窗体可点击
            this.setFocusable(true);
            ColorDrawable dw = new ColorDrawable(0xb0000000);//设置窗口的颜色
            this.setBackgroundDrawable(dw);
            view.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    dismiss();
                    return false;
                }
            });
        }
    }
}
